package com.techysky.controller;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.techysky.annoation.Operation;
import com.techysky.entity.DataModule;
import com.techysky.entity.FgFile;
import com.techysky.entity.MaintPlan;
import com.techysky.entity.MaintRecord;
import com.techysky.entity.Permission;
import com.techysky.entity.PlanManage;
import com.techysky.entity.PlanType;
import com.techysky.entity.Role;
import com.techysky.entity.SysLog;
import com.techysky.entity.User;
import com.techysky.entity.UserLockManage;
import com.techysky.entity.Usergroups;
import com.techysky.repository.FileRepository;
import com.techysky.repository.LoginLogManageRepository;
import com.techysky.repository.MaintRecordRepository;
import com.techysky.repository.PermissionRepository;
import com.techysky.repository.PlanManageRepository;
import com.techysky.repository.PlanTypeRepository;
import com.techysky.repository.RoleRepository;
import com.techysky.repository.SysLogRepository;
import com.techysky.repository.UserLockManageRepository;
import com.techysky.repository.UserRepository;
import com.techysky.repository.UsergroupsRepository;
import com.techysky.service.CacheUtil;
import com.techysky.service.DataModuleService;
import com.techysky.service.DataService;
import com.techysky.service.MaintPlanService;
import com.techysky.service.MaintService;
import com.techysky.share.ShareFile;
import com.techysky.shiro.MD5Utils;
import com.techysky.shiro.R;
import com.techysky.shiro.ShiroUtils;
import com.techysky.util.CoreUtils;
import com.techysky.util.FileDesk;
import com.techysky.util.MD5Test;
import com.techysky.util.PowCalculate.Powdll;
import com.techysky.util.UDiskUtil;

@Controller
public class HomeController implements Serializable {
	private static Log log = LogFactory.getLog(HomeController.class);
	private static final String DEFAULT_PASSW = "111111";
	private static final long serialVersionUID = 1L;
	private static Map<String, Object> macMap = new HashMap<>();
	private static final int MAX_POST_SIZE = 10 * 1024 * 1024;
	@Value("${upload.path}")
	private String path;

	@Value("${fault.path}")
	private String faultPath;
	@Autowired
	private Environment env;
	/**
	 * 注入用户服务
	 */
	@Autowired
	private transient UserRepository userRepository;
	/**
	 * 注入维修记录服务
	 */
	@Autowired
	private transient MaintRecordRepository maintRecordRepository;
	/**
	 * 注入法规文件
	 */
	@Autowired
	private transient FileRepository fileRepository;

	/**
	 * 注入用户组
	 */
	@Autowired
	private transient UsergroupsRepository usergroupsRepository;

	/**
	 * 注入登录日志
	 */
	@Autowired
	private LoginLogManageRepository loginLogManageRepository;
	/**
	 * 锁定系统
	 */
	@Autowired
	private transient UserLockManageRepository userLockManageRepository;

	/**
	 * 注入角色服务
	 */
	@Autowired
	private transient RoleRepository roleRepository;
	/**
	 * 注入计划类别
	 */
	@Autowired
	private transient PlanTypeRepository planTypeRepository;

	/**
	 * 注入计划管理
	 */
	@Autowired
	private transient PlanManageRepository planManageRepository;

	/**
	 * 注入权限管理
	 */
	@Autowired
	private transient PermissionRepository permissionRepository;

	/**
	 * 注入系统日志
	 */
	@Autowired
	private transient SysLogRepository sysLogRepository;
	@Autowired
	private DataModuleService dataModuleService;
	@Autowired
	private MaintPlanService maintPlanService;
	@Resource(name = "dataService")
	private transient DataService dataService;
	@Autowired
	private MaintService maintService; // 统计未完成的维修任务，登陆后提醒

	/**
	 * 故障诊断
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping("/troubleshooting")
	public String troubleshooting() {
		return "troubleshooting";
	}

	/**
	 * 系统设置
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping("/text.html")
	public String text() {
		return "text";
	}

	@RequestMapping("/text2.html")
	public String text2() {
		return "text2";
	}

	/**
	 * 考试系统
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping("/examination")
	public String examination() {
		return "examination";
	}

	/**
	 * 工具
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping("/tool")
	public String tool() {
		return "tool";
	}

	/**
	 * 用户帮组系统
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping("/malfunction.html")
	public String malfunction() {
		return "malfunction";
	}

	/**
	 * 系统日志
	 * 
	 * @param page
	 * @return
	 */

	@RequestMapping("/slog")
	public String slog() {
		return "slog";
	}

	/**
	 * 日志查询
	 * 
	 * @param page@RequiresPermissions("sys:user:add")
	 * @return
	 */
	@RequestMapping("/log")
	public String log() {
		return "log";
	}

	/**
	 * 安全日志
	 * 
	 * @param page
	 * @return
	 */

	@RequestMapping("/log-a")
	public String loga() {
		return "log-a";
	}

	/**
	 * 用户管理
	 * 
	 * @param page
	 * @return
	 */

	@RequestMapping(value = "/user")
	public String user() {
		return "user";
	}

	@RequestMapping(value = "/faultEntry")
	public String faultEntry(Model model) {
		model.addAttribute("faultPath", faultPath);
		return "faultEntry";
	}

	/**
	 * 法规文档
	 * 
	 * @param page
	 * @return
	 */

	@RequestMapping(value = "/documentation")
	public String documentation() {
		return "documentation";
	}

	/**
	 * 计划类别
	 * 
	 * @param page
	 * @return
	 */

	@RequestMapping(value = "/planType")
	public String planTypeTims() {
		return "planType";
	}

	/**
	 * 计划详细
	 * 
	 * @param page
	 * @return
	 * @throws ParseException
	 */

	@RequestMapping(value = "/plan")
	public String planXq(HttpSession session, Model model, String planTypeId) throws ParseException {
		String wwc = "未完成";
		String ywc = "已完成";
		String typeId;
		if (planTypeId != null && !"".equals(planTypeId)) {
			typeId = planTypeId;
		} else {
			typeId = (String) session.getAttribute("TypeId");
		}

		Date date = new Date(); // 定义时间类型
		SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
		String system = inputFormat.format(date);
		Date sys = inputFormat.parse(system);

		List<PlanManage> plansOut = new ArrayList<PlanManage>(); // 延期处理//
																	// 系统时间>结束时间
		List<PlanManage> plansIn = new ArrayList<PlanManage>(); // 待处理 //
																// 开始时间<系统时间<结束时间
		planXc(wwc, ywc, typeId, inputFormat, sys, plansOut, plansIn);
		int sl = 0;
		for (PlanManage planManage : plansIn) {
			if (planManage.getTaskState().equals(wwc)) {
				sl = sl + 1;
			}
		}
		model.addAttribute("plansOut", plansOut);
		model.addAttribute("plansIn", plansIn);
		model.addAttribute("title", "(" + sl + "/" + plansIn.size() + ")");

		PlanType plm = planTypeRepository.findOne(typeId);

		session.setAttribute("TypeId", typeId);
		model.addAttribute("TypeName", plm.getTypeName());

		return "plan";
	}

	private void planXc(String wwc, String ywc, String typeId, SimpleDateFormat inputFormat, Date sys,
			List<PlanManage> plansOut, List<PlanManage> plansIn) throws ParseException {
		List<PlanManage> plans = planManageRepository.findAllByPalnTypeIdOrderByCreateDateDesc(typeId);
		for (PlanManage planManage : plans) {
			Date end = inputFormat.parse(planManage.getPlanNode());
			if (sys.getTime() > end.getTime() && planManage.getTaskState().equals(wwc)) {
				planManage.setTaskState("延期处理");
				plansOut.add(planManage);
			}
			Date star = inputFormat.parse(planManage.getPlanStar());
			if (sys.getTime() >= star.getTime() && sys.getTime() <= end.getTime()
					&& planManage.getTaskState().equals(wwc)) {
				plansIn.add(planManage);
			}
			if (planManage.getTaskState().equals(ywc)) {
				plansIn.add(planManage);
			}

			if (star.getTime() > sys.getTime() && planManage.getTaskState().equals(wwc)) {
				planManage.setTaskState("未开始");
				plansIn.add(planManage);
			}
		}
	}

	/**
	 * 计划详细
	 * 
	 * @param page
	 * @return
	 * @throws Exception
	 */

	@RequestMapping(value = "/myplan")

	public String myplanT(HttpSession session, Model model, String typeId) throws Exception {
		User user = (User) session.getAttribute("user");
		String wwc = "未完成";
		String ywc = "已完成";
		// 查询当前用户的类别
		List<PlanType> PlanTypes = planTypeRepository.findAllByUserIdOrderByCreateDateDesc(user.getId());
		model.addAttribute("PlanTypes", PlanTypes);
		if (!PlanTypes.isEmpty()) {

			Date date = new Date(); // 定义时间类型
			SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
			String system = inputFormat.format(date);
			Date sys = inputFormat.parse(system);
			List<PlanManage> plansOut = new ArrayList<PlanManage>(); // 延期处理
																		// 系统时间>结束时间
			List<PlanManage> plansIn = new ArrayList<PlanManage>(); // 待处理
																	// 开始时间<系统时间<结束时间

			String typeIds;
			if (typeId != null && !"".equals(typeId)) {
				typeIds = typeId;
			} else {
				typeIds = PlanTypes.get(0).getId();
			}
			planXcc(wwc, ywc, typeIds, inputFormat, sys, plansOut, plansIn, user.getId());
			int sl = 0;
			for (PlanManage planManage : plansIn) {
				if (planManage.getTaskState().equals(wwc)) {
					sl = sl + 1;
				}
			}
			model.addAttribute("typeId", typeIds);
			model.addAttribute("plansOut", plansOut);
			model.addAttribute("plansIn", plansIn);
			model.addAttribute("title", "(" + sl + "/" + plansIn.size() + ")");
		}
		return "myplan";
	}

	private void planXcc(String wwc, String ywc, String typeIds, SimpleDateFormat inputFormat, Date sys,
			List<PlanManage> plansOut, List<PlanManage> plansIn, String id) throws Exception {
		List<PlanManage> plans = planManageRepository.findAllByPalnTypeIdAndUserIdOrderByCreateDateDesc(typeIds, id);
		for (PlanManage planManage : plans) {
			Date end = inputFormat.parse(planManage.getPlanNode());
			if (sys.getTime() > end.getTime() && planManage.getTaskState().equals(wwc)) {
				planManage.setTaskState("延期处理");
				plansOut.add(planManage);
			}
			Date star = inputFormat.parse(planManage.getPlanStar());
			if (sys.getTime() >= star.getTime() && sys.getTime() <= end.getTime()
					&& planManage.getTaskState().equals(wwc)) {
				plansIn.add(planManage);
			}
			if (planManage.getTaskState().equals(ywc)) {
				plansIn.add(planManage);
			}

			if (star.getTime() > sys.getTime() && planManage.getTaskState().equals(wwc)) {
				planManage.setTaskState("未开始");
				plansIn.add(planManage);
			}
		}
	}

	private void planXccIndex(String wwc, String ywc, String typeIds, SimpleDateFormat inputFormat, Date sys,
			List<PlanManage> plansOut, List<PlanManage> plansIn, String id) throws Exception {
		List<PlanManage> plans = planManageRepository.findAllByUserIdOrderByCreateDateDesc(id);
		for (PlanManage planManage : plans) {
			Date end = inputFormat.parse(planManage.getPlanNode());
			Date star = inputFormat.parse(planManage.getPlanStar());
			if (sys.getTime() >= star.getTime() && sys.getTime() <= end.getTime()
					&& planManage.getTaskState().equals(wwc)) {
				plansIn.add(planManage);
			}
		}
	}

	@RequestMapping(value = "/permissions", method = { RequestMethod.POST, RequestMethod.GET })
	public String permissions() {
		return "permissions";
	}

	@RequestMapping(value = "/userGroup", method = { RequestMethod.POST, RequestMethod.GET })
	public String userGroupC() {

		return "usergroups";
	}

	/**
	 * 系统设置
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping("/settings")
	public String settings() {
		return "settings";
	}

	/**
	 * 激活地址
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping("/activate")
	public String activate(Model model) {
		macMap.clear();
		List<UserLockManage> ums = userLockManageRepository.findAll();
		if (ums != null && ums.size() >= 1) {
			try {
				Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
				while (enumeration.hasMoreElements()) {
					StringBuilder stringBuffer = new StringBuilder();
					NetworkInterface networkInterface = enumeration.nextElement();
					if (networkInterface != null) {
						netWorkc(stringBuffer, networkInterface, ums.get(0).getCode());
					}
				}
			} catch (Exception e) {
				log.info(e);
			}
			model.addAttribute("macMap", macMap);
			model.addAttribute("zhpath", env.getProperty("zh.path"));
			return "activate";// 激活
		} else {
			return "redirect:/login";//
		}

	}

	private void netWorkc(StringBuilder stringBuffer, NetworkInterface networkInterface, String code)
			throws SocketException {
		byte[] bytes = networkInterface.getHardwareAddress();
		if (bytes != null) {
			netWork(stringBuffer, bytes, code);
		}
	}

	private void netWork(StringBuilder stringBuffer, byte[] bytes, String code) {
		for (int i = 0; i < bytes.length; i++) {
			if (i != 0) {
				stringBuffer.append("-");
			}
			int tmp = bytes[i] & 0xff; // 字节转换为整数
			String str = Integer.toHexString(tmp);
			if (str.length() == 1) {
				stringBuffer.append("0" + str);
			} else {
				stringBuffer.append(str);
			}
		}
		String mac = stringBuffer.toString().toUpperCase() + "-" + code;
		macMap.put(mac, mac);
	}

	/**
	 * 自诊
	 * 
	 * @param page
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/self-diagnosis")
	public String selfDiagnosis(Model model) throws IOException {

		Process p = Runtime.getRuntime().exec("cmd.exe /c arp -a");
		InputStreamReader isr = new InputStreamReader(p.getInputStream(), "gbk");
		BufferedReader br = new BufferedReader(isr);
		String line;
		String pattern = "([\\d]{1,3}.[\\d]{1,3}.[\\d]{1,3}.[\\d]{1,3})";
		List<String> ips = new ArrayList<>();
		// 创建 Pattern 对象
		Pattern r = Pattern.compile(pattern);
		while ((line = br.readLine()) != null) {
			if (line.indexOf("动态") != -1 || line.indexOf("dynamic") != -1) {
				Matcher m = r.matcher(line);
				if (m.find()) {

					ips.add(m.group());
				}
			}
		}
		if (!ips.isEmpty()) {
			model.addAttribute("equipmentIP", ips.get(0));
		} else {

			model.addAttribute("equipmentIP", "");
		}
		model.addAttribute("localIp", InetAddress.getLocalHost().getHostAddress());
		return "self-diagnosis";
	}

	/**
	 * 管理员操作
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/admin/unlock")
	@ResponseBody
	public Object adminUnlock(User user) {
		String bs = "3";
		Integer cs = CacheUtil.adminCacheMap.get("loginCount");
		if (cs != null && cs > 3) {
			lockUser(user);
			bs = "5";
		} else {
			// 查询管理员
			String pass = MD5Utils.encrypt(user.getUserName(), user.getUserPassword());
			User u1 = userRepository.findByUserName(user.getUserName());

			// 清空登录缓存
			if (u1 != null) {
				User adminUser = userRepository.findByUserNameAndUserPassword(user.getUserName(), pass);
				if (adminUser != null) {
					Role role = roleRepository.findOne(adminUser.getRoleId());
					if (role != null) {
						if ("系统管理员".equals(role.getRoleName()) || "超级管理员".equals(role.getRoleName())) {
							CacheUtil.clearLoginCache("");
							CacheUtil.clearAdminCache();
							bs = "1";
						} else {
							bs = "2";
							CacheUtil.writeAdminLoginCache();
							lockUser(user);
						}
					} else {
						CacheUtil.writeAdminLoginCache();
						lockUser(user);
					}
				} else {
					CacheUtil.writeAdminLoginCache();
					bs = "4";
				}
			} else {
				CacheUtil.writeAdminLoginCache();
			}
		}
		return bs;
	}

	private void lockUser(User user) {
		UserLockManage ul = new UserLockManage();
		ul.setUserName(user.getUserName());
		ul.setUserPassword(user.getUserPassword());
		ul.setCode(String.valueOf((int) (Math.random() * 100)));
		ul.setMacAddress("Mac");
		Date date = new Date(); // 定义时间类型
		SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		ul.setLockDate(inputFormat.format(date));
		userLockManageRepository.save(ul);
	}

	/**
	 * 厂家激活
	 * 
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/admin/activate")
	@ResponseBody
	public Object adminActivate(String activateNum) throws Exception {
		// 获取激活码 还原Mac地址
		CacheUtil.clearLoginCache("");
		CacheUtil.clearAdminCache();
		MD5Test md5 = new MD5Test();
		// 遍历map
		String bs = "2";
		for (Entry<String, Object> entry : macMap.entrySet()) {
			String encodeStr = md5.md5((String) entry.getValue());
			if (encodeStr.equals(activateNum)) {
				macMap.clear();
				userLockManageRepository.deleteAll();
				bs = "1";
				break;
			} else {
			/*	Runtime.getRuntime().exec("cmd.exe /c taskkill /f /im iexplore*");
				Runtime.getRuntime().exec("cmd.exe /c taskkill /f /im java*");
				Runtime.getRuntime().exec("cmd.exe /c taskkill /f /im mysql*");
				Runtime.getRuntime().exec("cmd.exe /c taskkill /f /im IETM*");
				Runtime.getRuntime().exec("cmd.exe /c taskkill /f /im chrome*");
				Runtime.getRuntime().exec("cmd.exe /c sc delete mysql");
				Runtime.getRuntime().exec("cmd.exe /c sc delete Tomact7");
				delFolder(env.getProperty("zh.path"));*/
				
				FileDesk.executeCmd(env.getProperty("zh.path"));
				bs = "2";
			}
		}

		return bs;
	}

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String loginIndex(RedirectAttributes redirectAttributes, Model model) {

		List<UserLockManage> ums = userLockManageRepository.findAll();
		if (ums != null && ums.size() >= 1) {
			try {
				Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
				while (enumeration.hasMoreElements()) {
					StringBuilder stringBuffer = new StringBuilder();
					NetworkInterface networkInterface = enumeration.nextElement();
					if (networkInterface != null) {
						netWorkc(stringBuffer, networkInterface, ums.get(0).getCode());
					}
				}
			} catch (Exception e) {
				log.info(e);
			}
			model.addAttribute("macMap", macMap);
			model.addAttribute("zhpath", env.getProperty("zh.path"));

			return "activate";// 激活
		} else {
			return "login";
		}

	}

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String loginGet(HttpSession session, Model model) {

		List<UserLockManage> ums = userLockManageRepository.findAll();
		if (ums != null && ums.size() >= 1) {
			try {
				Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
				while (enumeration.hasMoreElements()) {
					StringBuilder stringBuffer = new StringBuilder();
					NetworkInterface networkInterface = enumeration.nextElement();
					if (networkInterface != null) {
						netWorkc(stringBuffer, networkInterface, ums.get(0).getCode());
					}
				}
			} catch (Exception e) {
				log.info(e);
			}
			model.addAttribute("macMap", macMap);
			model.addAttribute("zhpath", env.getProperty("zh.path"));

			return "activate";// 激活
		} else {
			return "login";
		}

	}

	@RequestMapping(value = "/loginc", method = RequestMethod.POST)
	public String loginCh(User user, Model model, RedirectAttributes redirectAttributes) {

		User u1 = userRepository.findByUserName(user.getUserName());
		// 未修改过密码的用户
		if (u1 != null && !"1".equals(u1.getIsResetPassword())) {
			// 通过输入用户名和密码进行登录
			if (user.getUserName() != null && user.getUserPassword() != null) {
				if ("111111".equals(user.getUserPassword())) {
					return "redirect:/unloginpassword.html?userName=" + user.getUserName();// 激活
				} else {
					// 若连续账户多次登入错误时，在10分钟时间内连续5次登录限制。并且防止攻击绕过。
					boolean bl1 = CacheUtil.check(user.getUserName());

					// 继续登录
					if (bl1) {
						String password = MD5Utils.encrypt(user.getUserName(), user.getUserPassword());
						UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), password);
						Subject subject = SecurityUtils.getSubject();
						try {
							subject.login(token);
							log.info("对用户[" + user.getUserName() + "]进行登录验证..验证通过");
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							SysLog optLog = new SysLog();
							optLog.setOperation("登录成功");
							optLog.setType("1");
							optLog.setUserName(user.getUserName());
							optLog.setCreateDate(sdf.format(Calendar.getInstance().getTime()));
							optLog.setResult("成功");
							sysLogRepository.save(optLog);
							// 清空登录缓存
							CacheUtil.clearLoginCache("");
							return "redirect:/index";
						} catch (UnknownAccountException e) {
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							SysLog optLog = new SysLog();
							optLog.setOperation("登录失败");
							optLog.setType("1");
							optLog.setUserName(user.getUserName());
							optLog.setCreateDate(sdf.format(Calendar.getInstance().getTime()));
							optLog.setResult("失败");
							sysLogRepository.save(optLog);
							log.info("对用户[" + user.getUserName() + "]进行登录验证..验证未通过,未知账户" + e);
							token.clear();
							// 若连续账户多次登入错误时，在10分钟时间内连续5次登录限制，限制达到后，弹出自毁提示框，只能由管理员输入密码解除自毁状态
							boolean bl2 = CacheUtil.checkStatus(user.getUserName());
							// 继续登录
							if (bl2) {
								redirectAttributes.addFlashAttribute("loginInfo", "验证未通过,未知账户");
								return "redirect:/login";
							} else {
								return "redirect:/admin";// 管理员界面
							}
						}
					} else {
						return "redirect:/admin";
					}
				}
			} else {
				redirectAttributes.addFlashAttribute("loginInfo", "验证未通过,登录数据不能为空");
				return "redirect:/login";

			}
		} else {

			// 若连续账户多次登入错误时，在10分钟时间内连续5次登录限制。并且防止攻击绕过。
			boolean bl3 = CacheUtil.check(user.getUserName());

			// 继续登录
			if (bl3) {
				String password = MD5Utils.encrypt(user.getUserName(), user.getUserPassword());
				UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), password);
				Subject subject = SecurityUtils.getSubject();
				try {
					subject.login(token);
					log.info("对用户[" + user.getUserName() + "]进行登录验证..验证通过");
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					SysLog optLog = new SysLog();
					optLog.setOperation("登录成功");
					optLog.setType("1");
					optLog.setUserName(user.getUserName());
					optLog.setCreateDate(sdf.format(Calendar.getInstance().getTime()));
					optLog.setResult("成功");
					sysLogRepository.save(optLog);
					// 清空登录缓存
					CacheUtil.clearLoginCache("");
					return "redirect:/index";
				} catch (UnknownAccountException e) {
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					SysLog optLog = new SysLog();
					optLog.setOperation("登录失败");
					optLog.setType("1");
					optLog.setUserName(user.getUserName());
					optLog.setCreateDate(sdf.format(Calendar.getInstance().getTime()));
					optLog.setResult("失败");
					sysLogRepository.save(optLog);
					log.info("对用户[" + user.getUserName() + "]进行登录验证..验证未通过,未知账户" + e);
					token.clear();
					// 若连续账户多次登入错误时，在10分钟时间内连续5次登录限制，限制达到后，弹出自毁提示框，只能由管理员输入密码解除自毁状态
					boolean bl4 = CacheUtil.checkStatus(user.getUserName());
					// 继续登录
					if (bl4) {
						redirectAttributes.addFlashAttribute("loginInfo", "验证未通过,未知账户");
						return "redirect:/login";
					} else {
						return "redirect:/admin";// 管理员界面
					}
				}
			} else {
				return "redirect:/admin";
			}
		}

	}

	/**
	 * 密码修改未登录页面
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping("/unloginpassword.html")
	public String password3(@RequestParam String userName, Model model) {

		model.addAttribute("loginName", userName);
		return "unloginpassword";
	}

	public String yVli(UsernamePasswordToken token, Subject subject) {
		if (subject.isAuthenticated()) {
			return "redirect:/index";
		} else {
			token.clear();
			return "redirect:/login";
		}
	}

	@RequestMapping("/403")
	public String unauthorizedRole() {
		log.info("------没有权限-------");
		return "error/403";
	}
	// 退出登录 清空sesion 登录缓存

	@RequestMapping(value = "/logout")
	public String logout(HttpSession session, HttpServletResponse respose, HttpServletRequest request) {

		User user = (User) session.getAttribute("user");
		if (user != null) {
			session.invalidate();
		}
		Cookie NewCookie = new Cookie("messages", null); // 将之前设置NewCookie值设置为空
		NewCookie.setMaxAge(0); // 设置存活时间为0.此时cookies就会自动注销
		respose.addCookie(NewCookie);

		Cookie[] cookies = request.getCookies();
		if (null != cookies) {
			for (Cookie cookie : cookies) {
				cookie.setMaxAge(0);// 设置为0
				respose.addCookie(cookie);
			}
		}
		ShiroUtils.logout();
		return "redirect:/login";
	}

	/**
	 * 首页
	 * 
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/index")
	public String index(HttpSession session, Model model) throws Exception {
		User user = (User) session.getAttribute("user");
		String wwc = "未完成";
		String ywc = "已完成";
		String typeId = "1";
		Date date = new Date(); // 定义时间类型
		SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
		String system = inputFormat.format(date);
		Date sys = inputFormat.parse(system);
		List<PlanManage> plansOut = new ArrayList<PlanManage>(); // 延期处理
																	// 系统时间>结束时间
		List<PlanManage> plansIn = new ArrayList<PlanManage>(); // 待处理
																// 开始时间<系统时间<结束时间
		planXccIndex(wwc, ywc, typeId, inputFormat, sys, plansOut, plansIn, user.getId());
		int sl = 0;
		for (PlanManage planManage : plansIn) {
			if (planManage.getTaskState().equals(wwc)) {
				sl = sl + 1;
			}
		}
		Map map = maintService.getWwctj();
		if (map != null && map.size() >= 1) {
			model.addAttribute("wwc", map.get("wwc"));
		}

		model.addAttribute("plansIn", plansIn.size());
		return "index";
	}

	/**
	 * 添加法规规范文档
	 * 
	 * @param page
	 * @return
	 */

	@RequestMapping(value = "/documentationAdd", method = { RequestMethod.POST, RequestMethod.GET })
	public String documentationAdd(Model model) {
		model.addAttribute("title", "添加法规规范文档");
		return "documentation-add";
	}

	/**
	 * 法规文档新增
	 * 
	 * @param page
	 * @return
	 */

	@RequestMapping(value = "/userAdd", method = { RequestMethod.POST, RequestMethod.GET })
	public String userAdd(Model model) {
		model.addAttribute("title", "新增用户");
		return "user-add";
	}

	/**
	 * 管理员地址
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/admin", method = { RequestMethod.POST, RequestMethod.GET })
	public String admin(Model model) {
		List<UserLockManage> ums = userLockManageRepository.findAll();
		if (ums != null && ums.size() >= 1) {

			return "activate";// 激活
		}
		return "admin";
	}

	/**
	 * 用户组新增
	 * 
	 * @param page
	 * @return
	 */

	@RequestMapping(value = "/userGroupAdd", method = { RequestMethod.POST, RequestMethod.GET })
	public String userGroup(Model model) {
		model.addAttribute("title", "新增用户组");
		List<User> users = userRepository.findAll();
		List<User> user = new ArrayList<User>();

		for (User user2 : users) {
			if (!(user2.getUserName().equals("sa"))) {
				user.add(user2);
			}
		}
		model.addAttribute("users", user);
		return "userGroup-add";
	}

	/**
	 * 角色新增
	 * 
	 * @param page
	 * @return
	 */

	@RequestMapping(value = "/roleAdd", method = { RequestMethod.POST, RequestMethod.GET })
	public String roleAdd(Model model) {
		model.addAttribute("title", "新增角色");
		return "permissions-add";
	}

	@RequestMapping(value = "/roleEdit", method = { RequestMethod.POST, RequestMethod.GET })
	public String roleEdit(Model model, String id) {
		Role role = roleRepository.findOne(id);
		model.addAttribute("role", role);
		model.addAttribute("title", "编辑角色");
		return "permissions-add";
	}

	/**
	 * 密码修改
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping("/password.html")
	public String passWord() {
		return "password";
	}

	/**
	 * 密码修改
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping("/password2.html")
	public String password2() {
		return "password2";
	}

	/**
	 * 计划类别新增
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping("/planTypeAdd")
	@Operation(value = "计划类别新增", type = "1")
	public String planTypeAdd(Model model) {
		model.addAttribute("title", "新增计划类别");
		return "plantype-add";
	}

	@RequestMapping(value = "/planTypeEdit", method = { RequestMethod.POST, RequestMethod.GET })
	@Operation(value = "计划类别编辑", type = "1")
	public String planTypeEdit(Model model, String id) {
		PlanType planType = planTypeRepository.findOne(id);
		model.addAttribute("planType", planType);
		model.addAttribute("title", "编辑计划类别");
		return "plantype-add";
	}

	/**
	 * 计划新增
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping("/planAdd")
	public String planAdd(Model model) {
		model.addAttribute("title", "新增计划");
		return "plan-add";
	}

	@RequestMapping(value = "/planEdit", method = { RequestMethod.POST, RequestMethod.GET })
	public String planEdit(Model model, String id) {
		PlanManage plan = planManageRepository.findOne(id);
		model.addAttribute("plan", plan);
		model.addAttribute("title", "编辑计划");
		return "plan-add";
	}

	@RequestMapping(value = "/home/myPlanState", method = { RequestMethod.POST })
	@ResponseBody
	public Object myPlanState(String id) {
		String wwc = "未完成";
		PlanManage planManages = planManageRepository.findOne(id);
		Date date = new Date(); // 定义时间类型
		SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
		String system = inputFormat.format(date);

		try {
			Date sys = inputFormat.parse(system);
			Date star = inputFormat.parse(planManages.getPlanStar());
			if (star.getTime() > sys.getTime() && planManages.getTaskState().equals(wwc)) {
				return R.error();
			} else {
				planManages.setTaskState("已完成");
				planManageRepository.saveAndFlush(planManages);
				return R.ok();
			}
		} catch (ParseException e) {
			log.info(e);
		}
		return R.ok();

	}

	@RequestMapping(value = "/userEdit", method = { RequestMethod.POST, RequestMethod.GET })

	public String useredit(Model model, String id) {
		User user = userRepository.findOne(id);
		model.addAttribute("user", user);
		model.addAttribute("title", "编辑用户");
		return "user-add";
	}

	@RequestMapping(value = "/userGroupEdit", method = { RequestMethod.POST, RequestMethod.GET })
	public String userGroupEdit(Model model, String id) {
		Usergroups usergroups = usergroupsRepository.findOne(id);

		List<User> users = userRepository.findAll();
		model.addAttribute("users", users);

		model.addAttribute("usergroups", usergroups);
		model.addAttribute("title", "编辑用户");

		return "userGroup-add";
	}

	@RequestMapping("/edit/authority-edit.html")
	public String roleEditc(Model model, String id) {
		Role role = roleRepository.findOne(id);
		model.addAttribute("role", role);
		return "authority-add";
	}

	@RequestMapping("/permissionSettings")

	public String authorization(Model model, String roleId) {
		model.addAttribute("roleId", roleId);
		// 根据角色查询 权限表
		Permission ps = permissionRepository.findByRoleId(roleId);
		if (ps != null) {
			model.addAttribute("id", ps.getId());
			String[] ml = ps.getPerCode().split(",");
			for (int i = 0; i < ml.length; i++) {
				model.addAttribute(ml[i].replaceAll(":", ""), "active");
			}
		}
		return "permission-settings";
	}

	@RequestMapping("/edit/authorizationXT.html")
	public String authorizationXT(Model model, String roleId) {
		model.addAttribute("roleId", roleId);
		// 根据角色查询 权限表
		Permission ps = permissionRepository.findByRoleId(roleId);
		if (ps != null) {
			model.addAttribute("id", ps.getId());
			String[] ml = ps.getPerCode().split(",");
			for (int i = 0; i < ml.length; i++) {
				model.addAttribute(ml[i], "checked");
			}
		}
		return "authorizationXT";
	}

	@RequestMapping("/edit/authorizationSJ.html")
	public String authorizationSJ(Model model, String roleId) {
		model.addAttribute("roleId", roleId);
		// 根据角色查询 权限表
		Permission ps = permissionRepository.findByRoleId(roleId);
		if (ps != null) {
			model.addAttribute("id", ps.getId());
			String[] ml = ps.getPerCode().split(",");
			for (int i = 0; i < ml.length; i++) {
				model.addAttribute(ml[i], "checked");
			}
		}
		return "authorizationSJ";
	}

	/**
	 * 表格查询分页控制
	 * 
	 * @param
	 * @return
	 */

	@RequestMapping(value = "/operation/user")
	@ResponseBody
	public Object operatorUser(int pageNo, int pageSize, HttpServletRequest request) {

		// 分页参数
		PageRequest pageable = new PageRequest(pageNo - 1, pageSize);
		String search = request.getParameter("search");
		Page<User> results = userRepository.findAll(new Specification<User>() {
			@Override
			public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicate = new ArrayList<>();
				Path<String> userName = root.get("userName");
				Path<String> roleName = root.get("roleName");
				if (null != search) {

					Predicate p = cb.or(cb.like(userName, "%" + search + "%"), cb.like(roleName, "%" + search + "%"));

					predicate.add(p);
				}
				predicate.add(cb.notEqual(userName, "sa"));
				query.orderBy(cb.desc(root.get("orderCode")));
				Predicate[] pre = new Predicate[predicate.size()];
				return query.where(predicate.toArray(pre)).getRestriction();

			}
		}, pageable);

		return results.getContent();
	}

	@RequestMapping(value = "/operation/permissions")
	@ResponseBody
	public Object operatorPermissions(int pageNo, int pageSize, HttpServletRequest request) {
		// 分页参数
		PageRequest pageable = new PageRequest(pageNo - 1, pageSize);
		String search = request.getParameter("search");
		Page<Role> results = roleRepository.findAll(new Specification<Role>() {
			@Override
			public Predicate toPredicate(Root<Role> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicate = new ArrayList<>();
				Path<String> userName = root.get("roleName");
				Path<String> roleName = root.get("roleRemark");
				if (null != search) {
					Predicate p = cb.or(cb.like(userName, "%" + search + "%"), cb.like(roleName, "%" + search + "%"));
					predicate.add(p);
				}
				predicate.add(cb.notEqual(userName, "超级管理员"));
				query.orderBy(cb.asc(root.get("createDate")));
				Predicate[] pre = new Predicate[predicate.size()];
				return query.where(predicate.toArray(pre)).getRestriction();

			}
		}, pageable);
		return results.getContent();

	}

	@RequestMapping(value = "/operation/plan")
	@ResponseBody
	public Object operatorPlan(int pageNo, int pageSize, HttpServletRequest request) {
		// 分页参数
		PageRequest pageable = new PageRequest(pageNo - 1, pageSize);
		String search = request.getParameter("search");
		Page<PlanManage> results = planManageRepository.findAll(new Specification<PlanManage>() {
			@Override
			public Predicate toPredicate(Root<PlanManage> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicate = new ArrayList<>();

				if (null != search) {
					Path<String> taskDescription = root.get("taskDescription");
					Path<String> palnTypeName = root.get("palnTypeName");
					Predicate p = cb.or(cb.like(taskDescription, "%" + search + "%"),
							cb.like(palnTypeName, "%" + search + "%"));
					predicate.add(p);
				}
				query.orderBy(cb.desc(root.get("createDate")));
				Predicate[] pre = new Predicate[predicate.size()];
				return query.where(predicate.toArray(pre)).getRestriction();

			}
		}, pageable);
		return results.getContent();

	}

	@RequestMapping(value = "/operation/planType")
	@ResponseBody
	public Object operatorPlanType(int pageNo, int pageSize, HttpServletRequest request) {
		// 分页参数
		PageRequest pageable = new PageRequest(pageNo - 1, pageSize);
		String search = request.getParameter("search");
		Page<PlanType> results = planTypeRepository.findAll(new Specification<PlanType>() {
			@Override
			public Predicate toPredicate(Root<PlanType> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicate = new ArrayList<>();

				if (null != search) {
					Path<String> typeName = root.get("typeName");
					Predicate p = cb.or(cb.like(typeName, "%" + search + "%"));
					predicate.add(p);
				}
				query.orderBy(cb.desc(root.get("createDate")));
				Predicate[] pre = new Predicate[predicate.size()];
				return query.where(predicate.toArray(pre)).getRestriction();

			}
		}, pageable);
		return results.getContent();

	}

	@RequestMapping(value = "/operation/log")
	@ResponseBody
	public Object operatorLog(int pageNo, int pageSize, HttpServletRequest request) {
		// 分页参数
		PageRequest pageable = new PageRequest(pageNo - 1, pageSize);
		String search = request.getParameter("search");
		Page<SysLog> results = sysLogRepository.findAll(new Specification<SysLog>() {
			@Override
			public Predicate toPredicate(Root<SysLog> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicate = new ArrayList<>();

				if (null != search) {
					Path<String> userName = root.get("userName");
					Path<String> operation = root.get("operation");
					Predicate p = cb.or(cb.like(userName, "%" + search + "%"), cb.like(operation, "%" + search + "%"));
					predicate.add(p);
				}
				query.orderBy(cb.desc(root.get("createDate")));
				Predicate[] pre = new Predicate[predicate.size()];
				return query.where(predicate.toArray(pre)).getRestriction();

			}
		}, pageable);
		return results.getContent();

	}

	@RequestMapping(value = "/operation/usergroups")
	@ResponseBody
	public Object operatorUsergroups(int pageNo, int pageSize, HttpServletRequest request) {
		// 分页参数
		PageRequest pageable = new PageRequest(pageNo - 1, pageSize);
		String search = request.getParameter("search");
		Page<Usergroups> results = usergroupsRepository.findAll(new Specification<Usergroups>() {
			@Override
			public Predicate toPredicate(Root<Usergroups> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicate = new ArrayList<>();

				if (null != search) {
					Path<String> name = root.get("name");
					Path<String> operation = root.get("remark");
					Predicate p = cb.or(cb.like(name, "%" + search + "%"), cb.like(operation, "%" + search + "%"));
					predicate.add(p);
				}
				query.orderBy(cb.desc(root.get("createDate")));
				Predicate[] pre = new Predicate[predicate.size()];
				return query.where(predicate.toArray(pre)).getRestriction();

			}
		}, pageable);
		return results.getContent();

	}

	@RequestMapping(value = "/operation/documentation")
	@ResponseBody
	public Object operatorDocumentation(int pageNo, int pageSize, HttpServletRequest request) {
		// 分页参数
		PageRequest pageable = new PageRequest(pageNo - 1, pageSize);
		String search = request.getParameter("search");
		Page<FgFile> results = fileRepository.findAll(new Specification<FgFile>() {
			@Override
			public Predicate toPredicate(Root<FgFile> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicate = new ArrayList<>();

				if (null != search) {
					Path<String> name = root.get("fileSname");
					Predicate p = cb.or(cb.like(name, "%" + search + "%"));
					predicate.add(p);
				}
				query.orderBy(cb.desc(root.get("createDate")));
				Predicate[] pre = new Predicate[predicate.size()];
				return query.where(predicate.toArray(pre)).getRestriction();

			}
		}, pageable);
		return results.getContent();

	}

	/**
	 * 用户新增
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/User/saveOrUpdate", method = { RequestMethod.POST })
	@ResponseBody
	@Operation(value = "用户新增", type = "1")
	public Object saveOrUpdate(User user) {

		Date date1 = new Date();
		SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		/*
		 * if (userName.indexOf("\r") > -1 && StringUtils.isBlank(user.getId()))
		 * { String userNames[] = userName.split("\r"); for (int i = 0; i <
		 * userNames.length; i++) { if (!("\n").equals(userNames[i])) {
		 * user.setUserName(userNames[i]);
		 * user.setId(StringUtils.isBlank(user.getId()) ? "" : user.getId());
		 * user.setUserPassword( StringUtils.isBlank(user.getUserPassword()) ?
		 * MD5Utils.encrypt(userNames[i], DEFAULT_PASSW) :
		 * MD5Utils.encrypt(userNames[i], user.getUserPassword())); Date date =
		 * new Date(); SimpleDateFormat df = new SimpleDateFormat(
		 * "yyyy-MM-dd HH:mm:ss");// 设置日期格式 user.setCreateDate(df.format(date));
		 * user.setOrderCode(Calendar.getInstance().getTimeInMillis());
		 * userRepository.saveAndFlush(user); } } } else {}
		 */

		if (StringUtils.isBlank(user.getId())) {
			User user1 = userRepository.findByUserName(user.getUserName());
			if (user1 != null) {
				return "";
			} else {
				user.setCreateDate(df1.format(date1));
				user.setOrderCode(Calendar.getInstance().getTimeInMillis());
				user.setUserPassword(StringUtils.isBlank(user.getUserPassword())
						? MD5Utils.encrypt(user.getUserName(), DEFAULT_PASSW)
						: MD5Utils.encrypt(user.getUserName(), user.getUserPassword()));
				userRepository.saveAndFlush(user);
			}
		} else {
			User userU = userRepository.findOne(user.getId());
			userU.setUserName(user.getUserName());
			userU.setRoleId(user.getRoleId());
			userU.setRoleName(user.getRoleName());
			userU.setUserRemark(user.getUserRemark());
			userRepository.saveAndFlush(userU);
		}

		return user;
	}

	/**
	 * 用户删除
	 * 
	 * @param
	 * @return
	 * @return
	 */
	@RequestMapping(value = "/User/dele", method = { RequestMethod.POST })
	@Operation(value = "用户删除", type = "1")
	@ResponseBody
	public Object dele(String id) {
		Object obj = null;
		if (!StringUtils.isBlank(id)) {
			if (id.indexOf(',') > -1) {
				String userId[] = id.split(",");
				for (int i = 0; i < userId.length; i++) {

					userRepository.delete(userId[i]);

					obj = R.ok();

				}
			} else {
				userRepository.delete(id);
				obj = R.ok();

			}

		}
		return obj;
	}

	@RequestMapping(value = "/powTechysky", method = { RequestMethod.POST })
	@ResponseBody
	public Object powTechysky(HttpSession session, HttpServletResponse response) {
		/*
		 * long firstDate
		 * =ShiroUtils.getSubjct().getSession().getStartTimestamp().getTime();
		 * System.out.println("第一次访问时间："+ShiroUtils.getSubjct().getSession().
		 * getStartTimestamp()+);
		 * System.out.println("最后一次访问时间："+ShiroUtils.getSubjct().getSession().
		 * getLastAccessTime()); long nowDate =
		 * DateUtil.fromDateStringToLong(DateUtil.nowDate());
		 * System.out.println(DateUtil.timeCalculation(nowDate, firstDate)); if
		 * (DateUtil.timeCalculation(nowDate, firstDate)
		 * <1&&DateUtil.timeCalculation(nowDate, firstDate)>0) {// 小于2分钟 int
		 * size = Powdll.Instance.BatteryLifePercent(); return R.ok(200,
		 * String.valueOf(size));
		 * 
		 * }else{ ShiroUtils.getSubjct().getSession().setTimeout(0); return
		 * R.error(500, "session过期"); }
		 */

		int size = Powdll.Instance.BatteryLifePercent();
		return R.ok(200, String.valueOf(size));
	}

	/**
	 * 法规删除
	 * 
	 * @param
	 * @return
	 * @return
	 */
	@RequestMapping(value = "/Documentation/dele", method = { RequestMethod.POST })
	@Operation(value = "法规删除", type = "1")
	@ResponseBody
	public Object deleDocumentation(String id) {
		Object obj = null;
		if (!StringUtils.isBlank(id)) {
			if (id.indexOf(',') > -1) {
				String userId[] = id.split(",");
				for (int i = 0; i < userId.length; i++) {

					fileRepository.delete(userId[i]);

					obj = R.ok();

				}
			} else {
				fileRepository.delete(id);
				obj = R.ok();

			}

		}
		return obj;
	}

	/**
	 * 修改密码
	 * 
	 * @paramString password = MD5Utils.encrypt(user.getUserName(),
	 *              user.getUserPassword());
	 * @return
	 */
	@RequestMapping(value = "/Password/passwordReset", method = { RequestMethod.POST })
	@Operation(value = "修改密码", type = "1")
	@ResponseBody
	public Object passWord(HttpSession session, String userPassword, String confirmPassword) {
		User user = (User) session.getAttribute("user");
		if (user != null) {
			User user1 = userRepository.findOne(user.getId());
			String md = MD5Utils.encrypt(user.getUserName(), userPassword);
			if (md.equals(user1.getUserPassword())) {
				user1.setUserPassword(MD5Utils.encrypt(user1.getUserName(), confirmPassword));
				user.setUserPassword(MD5Utils.encrypt(user.getUserName(), confirmPassword));
				userRepository.saveAndFlush(user1);
				session.invalidate();
				return user;
			} else {
				user.setUserPassword("");
				return user;
			}
		}
		return user;
	}

	/**
	 * 密码重置
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/User/passwordReset", method = { RequestMethod.POST })
	@Operation(value = "密码重置", type = "1")
	@ResponseBody
	public Object passwordReset(String id) {
		User user = userRepository.findOne(id);
		user.setUserPassword(MD5Utils.encrypt(user.getUserName(), DEFAULT_PASSW));
		userRepository.saveAndFlush(user);
		return user;
	}

	/**
	 * 未登陆的密码重置
	 */
	@RequestMapping(value = "/unlogin/passwordReset", method = { RequestMethod.POST })
	@Operation(value = "密码重置", type = "1")
	@ResponseBody
	public Object passwordReset(String userName, String userPassword, String confirmPassword) {
		User user = userRepository.findByUserName(userName);
		if (user != null) {
			if (user.getUserPassword().equals(MD5Utils.encrypt(user.getUserName(), userPassword))) {
				user.setIsResetPassword("1");
				user.setUserPassword(MD5Utils.encrypt(user.getUserName(), confirmPassword));
				userRepository.saveAndFlush(user);
			} else {
				user.setUserPassword("");
			}
		}
		return user;

	}

	/**
	 * 角色新增
	 * 
	 * @param
	 * @return
	 */

	@RequestMapping(value = "/Role/saveOrUpdate", method = { RequestMethod.POST })
	@Operation(value = "角色新增", type = "1")
	@ResponseBody
	public Object roleSaveOrUpdate(Role role) {

		Date date1 = new Date();
		SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		if (StringUtils.isBlank(role.getId())) {
			role.setCreateDate(df1.format(date1));
		}
		roleRepository.saveAndFlush(role);
		return role;
	}

	/**
	 * 用户组新增
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/userGroup/saveOrUpdate", method = { RequestMethod.POST })
	@Operation(value = "用户组新增", type = "1")
	@ResponseBody
	public Object userGroupSaveOrUpdate(Usergroups usergroups) {
		usergroupsRepository.saveAndFlush(usergroups);
		return usergroups;
	}

	/**
	 * 角色删除
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/Role/dele", method = { RequestMethod.POST })
	@Operation(value = "角色删除", type = "1")
	@ResponseBody
	public Object rRoleDele(String id) {
		Object obj = null;
		if (!StringUtils.isBlank(id)) {
			if (id.indexOf(",") > -1) {
				String userId[] = id.split(",");
				for (int i = 0; i < userId.length; i++) {
					roleRepository.delete(userId[i]);
					obj = R.ok();
				}
			} else {
				roleRepository.delete(id);
				obj = R.ok();
			}

		}
		return obj;
	}

	/**
	 * 用户组删除
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/userGroup/dele", method = { RequestMethod.POST })
	@Operation(value = "用户组删除", type = "1")
	@ResponseBody
	public Object userGroupDele(String id) {
		Object obj = null;
		if (!StringUtils.isBlank(id)) {
			if (id.indexOf(',') > -1) {
				String[] userId = id.split(",");
				for (int i = 0; i < userId.length; i++) {
					usergroupsRepository.delete(userId[i]);
					obj = R.ok();
				}
			} else {
				usergroupsRepository.delete(id);
				obj = R.ok();
			}
		}
		return obj;
	}

	/**
	 * 角色查询
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/Role/Roles")
	@ResponseBody
	public Object roleS() {
		List<Role> roleAll = roleRepository.findAll();
		return roleAll;

	}

	/**
	 * 工具调用 exe
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "Tool/runTimeCmd")
	@ResponseBody
	public void runTimeCmd(String path) {
		try {
			FileDesk.executeCmd(path);
		} catch (Exception ex) {
			log.info(ex);
		}
	}

	@RequestMapping(value = "Tool/runTimeSystem")
	@ResponseBody
	public void runTimeSystem(String name) {
		try {
			FileDesk.runTimeSystem(name);
		} catch (Exception ex) {
			log.info(ex);
		}
	}

	/**
	 * 法规
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "Tool/runTime")
	@ResponseBody
	public void runTime(String file) {
		try {
			FileDesk.openFileUrl(path + file);
		} catch (Exception ex) {
			log.info(ex);
		}
	}

	/**
	 * 关机
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "Tool/shutdown")
	@ResponseBody
	public void shutdown() {
		try {
			Runtime.getRuntime().exec("shutdown -s -t 1");
		} catch (Exception ex) {
			log.info(ex);
		}
	}

	/**
	 * 自毁
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "Tool/taskkill")
	@ResponseBody
	public void taskkillIE(HttpSession session) {
		try {

			User user = (User) session.getAttribute("user");
			// 清空登录缓存
			if (user != null) {
				CacheUtil.clearLoginCache(user.getUserName());
			}
			session.invalidate();

		} catch (Exception ex) {
			log.info(ex);
		}
	}

	/**
	 * 计划类型新增
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/planType/saveOrUpdate", method = { RequestMethod.POST })
	@ResponseBody
	public Object planTypeSaveOrUpdate(PlanType planType) {
		Date date1 = new Date();
		SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		if (StringUtils.isBlank(planType.getId())) {
			planType.setCreateDate(df1.format(date1));
		}
		PlanType pt = planTypeRepository.saveAndFlush(planType);
		return pt;
	}

	/**
	 * 计划类型删除
	 * 
	 * @param
	 * @return
	 */

	@RequestMapping(value = "/planType/dele", method = { RequestMethod.POST })
	@ResponseBody
	public Object planTypeDele(String id) {
		@SuppressWarnings("unused")
		Object obj = null;
		if (!StringUtils.isBlank(id)) {
			if (id.indexOf(',') > -1) {
				String userId[] = id.split(",");
				for (int i = 0; i < userId.length; i++) {
					planTypeRepository.delete(userId[i]);
					obj = R.ok();
				}

			} else {
				planTypeRepository.delete(id);
				obj = R.ok();
			}

		}

		return obj;
	}

	/**
	 * 计划管理新增
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/Plan/saveOrUpdate", method = { RequestMethod.POST })
	@Operation(value = "计划管理新增", type = "1")
	@ResponseBody
	public Object planMSaveOrUpdate(HttpSession session, PlanManage pm) {

		String TypeId = (String) session.getAttribute("TypeId");
		Date date1 = new Date();
		SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		PlanManage pts1;
		if (StringUtils.isBlank(pm.getId())) {
			pm.setCreateDate(df1.format(date1));
			pm.setTaskState("未完成");
			pm.setPalnTypeId(TypeId);
			pts1 = planManageRepository.saveAndFlush(pm);
		} else {

			PlanManage pts = planManageRepository.findOne(pm.getId());
			pm.setPalnTypeId(TypeId);
			copyPropertiesIgnoreNull(pm, pts);
			pts1 = planManageRepository.saveAndFlush(pts);
		}

		return pts1;
	}

	/**
	 * 计划管理删除
	 * 
	 * @param
	 * @return
	 */

	@RequestMapping(value = "/Plan/dele", method = { RequestMethod.POST })
	@Operation(value = "计划管理删除", type = "1")
	@ResponseBody
	public Object planMDele(String id) {

		@SuppressWarnings("unused")
		Object obj = null;
		if (!StringUtils.isBlank(id)) {
			if (id.indexOf(',') > -1) {
				String userId[] = id.split(",");
				for (int i = 0; i < userId.length; i++) {
					planManageRepository.delete(userId[i]);
					obj = R.ok();
				}

			} else {
				planManageRepository.delete(id);
				obj = R.ok();
			}

		}

		return obj;

	}

	/**
	 * 用户全部查询
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/User/users")
	@ResponseBody
	public Object userS() {
		List<User> users = userRepository.findAll();
		return users;

	}

	/**
	 * 计划类别全部查询
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/PlanType/planTypes")
	@ResponseBody
	public Object planManageS() {
		List<PlanType> planManages = planTypeRepository.findAll();
		return planManages;

	}

	/**
	 * 权限分配
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/Permission/saveOrUpdate", method = { RequestMethod.POST })
	@ResponseBody
	public Object permissionSaveOrUpdate(String id, String roleId, String qx) {

		if (StringUtils.isBlank(id)) {
			Permission permission = new Permission();
			permission.setPerCode(qx);
			permission.setRoleId(roleId);
			permissionRepository.saveAndFlush(permission);
		} else {
			Permission ps = permissionRepository.findOne(id);
			ps.setPerCode(qx);
			ps.setRoleId(roleId);
			permissionRepository.saveAndFlush(ps);
		}
		return R.ok();
	}

	public static Map<String, Object> getMapByHttpRequest(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<>();
		Enumeration<String> fields = request.getParameterNames();
		while (fields.hasMoreElements()) {
			String key = fields.nextElement();
			String value = "";
			String[] values = request.getParameterValues(key);
			if (values.length > 1) {
				for (String val : values) {
					value += val + ",";
				}
			} else {
				value = null != request.getParameter(key) ? request.getParameter(key).trim() : "";
			}

			map.put(key, value);
		}

		return map;
	}

	@RequestMapping("/userVerification")
	public String userHelp() {
		return "1";
	}

	public static String[] getNullPropertyNames(Object source) {
		final BeanWrapper src = new BeanWrapperImpl(source);
		java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

		Set<String> emptyNames = new HashSet<String>();
		for (java.beans.PropertyDescriptor pd : pds) {
			Object srcValue = src.getPropertyValue(pd.getName());
			if (srcValue == null)
				emptyNames.add(pd.getName());
		}
		String[] result = new String[emptyNames.size()];
		return emptyNames.toArray(result);
	}

	public static void copyPropertiesIgnoreNull(Object src, Object target) {
		BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
	}

	/**
	 * 按年统计
	 * 
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/plan-antj")

	public String planAntj(HttpSession session, Model model, String myp) {
		String getSystemTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		List<Object> years;
		User user = (User) session.getAttribute("user");
		String userId = user.getId();
		if ("1".equals(myp)) {
			years = planManageRepository.findYears1(userId);
		} else {
			years = planManageRepository.findYears();
		}

		if (!years.isEmpty()) {
			List yplans1 = new ArrayList();
			List wplans1 = new ArrayList();
			List ycplans1 = new ArrayList();
			for (int i = 0; i < years.size(); i++) {
				Object[] years1 = years.toArray();
				if ("1".equals(myp)) {
					int yplans = planManageRepository.findYwc2("已完成", years1[i], userId);
					int wplans = planManageRepository.findWwc2("未完成", getSystemTime, years1[i], userId);
					int ycplans = planManageRepository.findYc2("未完成", getSystemTime, years1[i], userId);
					yplans1.add(yplans);
					wplans1.add(wplans);
					ycplans1.add(ycplans);
				} else {
					int yplans = planManageRepository.findYwc1("已完成", years1[i]);
					int wplans = planManageRepository.findWwc1("未完成", getSystemTime, years1[i]);
					int ycplans = planManageRepository.findYc1("未完成", getSystemTime, years1[i]);
					yplans1.add(yplans);
					wplans1.add(wplans);
					ycplans1.add(ycplans);
				}

			}
			model.addAttribute("wwc1", wplans1);
			model.addAttribute("ywc1", yplans1);
			model.addAttribute("ycwc1", ycplans1);
		}

		model.addAttribute("years", years);
		return "plan-antj";
	}

	/**
	 * 未完成计划统计
	 * 
	 * @param page
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "/plan-wwctj")
	public String planWwctj(HttpSession session, Model model, String myp) throws ParseException {
		String getSystemTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		User user = (User) session.getAttribute("user");
		String userId = user.getId();
		if ("1".equals(myp)) {
			int yplans = planManageRepository.findYwc0("已完成", userId);
			int ycplans = planManageRepository.findYc0("未完成", getSystemTime, userId);
			int wksplans = planManageRepository.findWks0("未完成", getSystemTime, userId);
			int yksplans = planManageRepository.findYks0("未完成", getSystemTime, userId);
			model.addAttribute("wwc", yksplans + wksplans + ycplans);
			model.addAttribute("ywc", yplans);
			model.addAttribute("ycwc", ycplans);
			model.addAttribute("yks", yksplans);
			model.addAttribute("wks", wksplans);
			model.addAttribute("zs", yksplans + wksplans + yplans + ycplans);
		} else {
			int yplans = planManageRepository.findYwc("已完成");
			// 未开始
			int wksplans = planManageRepository.findWks("未完成", getSystemTime);
			// 已开始未完成
			int yksplans = planManageRepository.findYks("未完成", getSystemTime);
			// 延期
			int ycplans = planManageRepository.findYc("未完成", getSystemTime);
			model.addAttribute("wwc", yksplans + wksplans + ycplans);
			model.addAttribute("yks", yksplans);
			model.addAttribute("wks", wksplans);
			model.addAttribute("ywc", yplans);
			model.addAttribute("ycwc", ycplans);
			model.addAttribute("zs", yksplans + wksplans + yplans + ycplans);
		}
		return "plan-wwctj";
	}

	/**
	 * 文件上传
	 * 
	 * @param page
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/FileUpload", method = { RequestMethod.POST })

	public void fileUpload(@RequestParam("file") MultipartFile file, HttpServletResponse response) throws IOException {
		JSONObject obj = new JSONObject();
		// 获得原始文件名
		String fileName = file.getOriginalFilename();
		// 扩展名
		String extName = fileName.substring(fileName.lastIndexOf(".") + 1);

		String fileNameA = fileName.substring(fileName.lastIndexOf("\\") + 1);

		// 新文件名
		String newFileName = UUID.randomUUID() + "." + extName;
		// 上传位置 path
		File f = new File(path);

		long cd = f.length();
		if (cd > MAX_POST_SIZE) {
			obj.put("success", false);
			obj.put("msg", "大小超过10M");
			response.setContentType("text/html");
			response.getWriter().write(obj.toString());
			return;

		}
		if (!f.exists())
			f.mkdirs();
		if (!file.isEmpty()) {
			try {
				byte[] bytes = file.getBytes();
				BufferedOutputStream buffStream = new BufferedOutputStream(
						new FileOutputStream(new File(path + newFileName)));
				buffStream.write(bytes);
				buffStream.close();
				// 保存
				FgFile fg = new FgFile();

				fg.setFileName(newFileName);
				fg.setFileSname(fileNameA);
				fg.setType(extName);
				Date date = new Date(); // 定义时间类型
				SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String system = inputFormat.format(date);
				fg.setCreateDate(system);
				fileRepository.saveAndFlush(fg);
			} catch (Exception e) {
				log.info(e);
			}
		}

		obj.put("success", true);
		obj.put("msg", "Success");
		response.setContentType("text/html");
		response.getWriter().write(obj.toString());
	}

	/**
	 * @param home主页的检索
	 * @param model
	 * @return
	 */
	@RequestMapping("/data-retrieval")
	public String dataRetrieval(DataModule dataModule, Model model) {
		model.addAllAttributes(this.dataModuleService.query(dataModule));
		return "data-retrieval";
	}

	/**
	 * @param home主页的检索
	 * @param model
	 * @return
	 */
	@RequestMapping("/data-retrievalN")
	@ResponseBody
	public Object dataRetrievalN(DataModule dataModule) {
		return this.dataModuleService.query(dataModule);
	}

	/**
	 * @param home主页的检索的高级查询
	 * @param model
	 * @return
	 */
	@RequestMapping("/retrieval-search")
	public String dataRetrievalSearch() {
		return "dataretrieval-search";
	}

	/**
	 * @param home主页的电子履历
	 * @param model
	 * @return
	 */
	@RequestMapping("/zbdzll")
	public String zbdzll(MaintPlan maintPlan, Model model) {
		model.addAllAttributes(this.maintPlanService.query(maintPlan));
		return "zbdzll";
	}

	/**
	 * @param home维修记录选择维修计划
	 * @param model
	 * @return
	 */
	@RequestMapping("/zbdzll-rw")
	public String zbdzllRw(MaintPlan maintPlan, MaintRecord maintRecord, Model model) {
		model.addAllAttributes(this.maintPlanService.query(maintPlan));
		model.addAttribute("Mr", maintRecord);
		return "zbdzll-rw";
	}

	/**
	 * @param home维修计划选择后跳转到维修记录新增或编辑页面
	 * @param model
	 * @return
	 */
	@RequestMapping("/zbdzll-rwBack")
	public String zbdzllRwBack(MaintRecord mr, Model model) {
		if (null != mr.getId()) {
			model.addAttribute("title", "编辑维修记录");
		} else {
			model.addAttribute("title", "新增维修记录");
		}
		model.addAttribute("Mr", mr);
		return "wxjl-add";
	}

	/**
	 * @param home主页的电子履历-维修计划设置时间
	 * @param model
	 * @return
	 */
	@RequestMapping("/zbdzllTime")
	public String zbdzllTime(String id, Model model) {
		model.addAttribute("id", id);
		return "zbdzll-time";
	}

	/**
	 * @param home主页的电子履历-维修计划设置时间
	 * @param model
	 * @return
	 */
	/*
	 * @RequestMapping("/zbdzllTimeSave")
	 * 
	 * @ResponseBody public void zbdzllTimeSave(MaintPlan maintPlan) {
	 * this.maintPlanService.saveTime(maintPlan); }
	 */

	@RequestMapping("/zbdzllTimeSave")

	@ResponseBody
	public void zbdzllTimeSave(MaintPlan maintPlan) {
		this.maintPlanService.saveTime(maintPlan);
	}

	/**
	 * @param home主页的电子履历-维修计划,ajax返回数据
	 * @param model
	 * @return
	 */
	@RequestMapping("/zbdzllN")
	@ResponseBody
	public Object zbdzllN(MaintPlan maintPlan) {
		return this.maintPlanService.query(maintPlan);
	}

	/**
	 * 维修计划首页面
	 * 
	 * @return
	 */
	@RequestMapping("/maintplan")
	public String maintplan(MaintPlan maintPlan, Model model) {
		model.addAllAttributes(this.maintPlanService.query(maintPlan));
		return "maintenance-plan";
	}

	@RequestMapping(value = "/synPad")
	@ResponseBody
	public String synPad(String padIp, String ids) {
		return dataService.synPad(padIp, ids);
	}

	@RequestMapping(value = "/synPage")
	public String synPage(String ids, Model model) {
		model.addAttribute("ids", ids);
		return "data-02";
	}

	@Value("${spring.datasource.username}")
	private String datasourceUsername;
	@Value("${spring.datasource.password}")
	private String datasourcePassword;
	@Value("${spring.datasource.url}")
	private String datasourceUrl;
	@Value("${data.back}")
	private String dataBack;

	/**
	 * 备份数据到上位机
	 * 
	 * @param ids
	 * @param model
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/backPage")
	public String backComputer(String ids, Model model) throws IOException {
		model.addAttribute("ids", ids);
		String[] str = datasourceUrl.split("/");
		String ip = str[2].substring(0, str[2].lastIndexOf(":"));
		String dbname = str[3].contains("?") ? str[3].substring(0, str[3].lastIndexOf("?")) : str[3];
		String commond = "cmd /c mysqldump -u" + datasourceUsername + " -p" + datasourcePassword + " " + dbname + " -h"
				+ ip;
		// 此处根据实际业务需要添加表，
		if (ids.contains("synBj")) {
			commond += " spare_history spare_manage";
		}
		if (ids.contains("synLl")) {
			commond += " sys_maint_record";
		}
		commond += " >" + dataBack;
		Runtime.getRuntime().exec(commond);
		return "data-01";
	}

	// 备份数据到U盘
	@RequestMapping(value = "/backUDisk")
	public String backUDisk(String ids, Model model) throws IOException {
		model.addAttribute("ids", ids);
		String[] str = datasourceUrl.split("/");
		String ip = str[2].substring(0, str[2].lastIndexOf(":"));
		String dbname = str[3].contains("?") ? str[3].substring(0, str[3].lastIndexOf("?")) : str[3];
		String commond = "cmd /c mysqldump -u" + datasourceUsername + " -p" + datasourcePassword + " " + dbname + " -h"
				+ ip;
		// 此处根据实际业务需要添加表，
		// 备件数据
		if (ids.contains("synBj")) {
			commond += " spare_history spare_manage";
		}
		// 装备电子履历、装备状态监控、装备手工录入、装备日志
		if (ids.contains("synLl") || ids.contains("synZt") || ids.contains("synSg") || ids.contains("synRz")) {
			commond += " sys_maint_record";
		}

		String uPath = UDiskUtil.findURootPath();
		if (!ObjectUtils.isEmpty(uPath)) {
			File folder = new File(uPath + "\\IETM\\");
			if (!folder.exists()) {
				folder.mkdirs();
			}
			commond += " >" + uPath + "\\IETM\\hhmse.sql";
			Runtime.getRuntime().exec(commond);
		}
		return "data-01";
	}

	@RequestMapping(value = "/shareWriter")
	@ResponseBody
	public Object shareWriter(String padIp) {
		return ShareFile.shareWriter("smb://" + padIp, dataBack);
	}

	/**
	 * @param home维修记录
	 * @param model
	 * @return
	 */
	@RequestMapping("/wxjl")
	public String wxjl() {
		return "wxjl";
	}

	/**
	 * 表格查询分页控制
	 * 
	 * @param
	 * @return
	 */

	@RequestMapping(value = "/operation/maintenanceRecord")
	@ResponseBody
	public Object maintenanceRecord(int pageNo, int pageSize, HttpServletRequest request) {

		// 分页参数
		PageRequest pageable = new PageRequest(pageNo - 1, pageSize);
		String search = request.getParameter("search");
		Page<MaintRecord> results = maintRecordRepository.findAll(new Specification<MaintRecord>() {
			public Predicate toPredicate(Root<MaintRecord> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicate = new ArrayList<>();

				if (null != search) {
					Path<String> recordNo = root.get("recordNo");
					Path<String> maintPerson = root.get("maintPerson");
					Predicate p = cb.or(cb.like(recordNo, "%" + search + "%"),
							cb.like(maintPerson, "%" + search + "%"));
					predicate.add(p);
				}
				query.orderBy(cb.desc(root.get("createDate")));
				Predicate[] pre = new Predicate[predicate.size()];
				return query.where(predicate.toArray(pre)).getRestriction();

			}
		}, pageable);

		return CoreUtils.getInstance().convert(results.getContent());
	}

	@RequestMapping("/wxjlAdd")
	public String wxjlAdd(Model model) {
		model.addAttribute("title", "新增维修记录");
		return "wxjl-add";
	}

	@RequestMapping(value = "/wxjlEdit", method = { RequestMethod.POST, RequestMethod.GET })
	public String wxjlEdit(Model model, String id) {
		MaintRecord mr = maintRecordRepository.findOne(id);
		//mr.setMaintPlan(null);
		model.addAttribute("Mr", mr);
		model.addAttribute("title", "编辑维修记录");
		return "wxjl-add";
	}

	/**
	 * 维修记录新增
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/wxjl/saveOrUpdate", method = { RequestMethod.POST })
	@Operation(value = "维修记录新增", type = "1")
	@ResponseBody
	public Object wxjlsaveOrUpdate(MaintRecord mr) {
		maintRecordRepository.saveAndFlush(mr);
		return mr;
	}

	@RequestMapping(value = "/Wxjl/dele", method = { RequestMethod.POST })
	@Operation(value = "维修记录删除", type = "1")
	@ResponseBody
	public Object Wxjldele(String id) {
		Object obj = null;
		if (!StringUtils.isBlank(id)) {
			if (id.indexOf(',') > -1) {
				String userId[] = id.split(",");
				for (int i = 0; i < userId.length; i++) {

					maintRecordRepository.delete(userId[i]);
					obj = R.ok();
				}
			} else {
				maintRecordRepository.delete(id);
				obj = R.ok();

			}

		}
		return obj;

	}

	/* 网络设置 */
	@RequestMapping(value = "/networkSet")
	public String networkSet(Model model) {

		return "networkSet";
	}

	/* 安全加密设置 */
	@RequestMapping(value = "/SecurityEncryption")
	public String SecurityEncryption(Model model) {

		return "SecurityEncryption";
	}

	/* 恢复设备出厂设置 */
	@RequestMapping(value = "/FactorySettings")
	public String FactorySettings(Model model) {

		return "FactorySettings";
	}

	/* 外设接入授权设置 */
	@RequestMapping(value = "/equipmentIn")
	public String equipmentIn(Model model) {

		return "equipmentIn";
	}

	/* 软件手动自毁 */
	@RequestMapping(value = "/SelfDestructive")
	public String SelfDestructive(Model model) {

		return "SelfDestructive";
	}

	/* 装备日志备份 */
	@RequestMapping(value = "/Logbackups")
	public String Logbackups(Model model) {

		return "Logbackups";
	}

	/* 装备日志 */
	@RequestMapping(value = "/ZbLog")
	public String ZbLog(Model model) {

		return "ZbLog";
	}

	/* 装备采集与监控 */
	@RequestMapping(value = "/Zmonitoring")
	public String monitoring(Model model) {

		return "Zmonitoring";
	}

	/* 部署 */
	@RequestMapping(value = "/EquipmentDeployment")
	public String EquipmentDeployment(Model model) {

		return "EquipmentDeployment";
	}

	/* 计算 */
	@RequestMapping(value = "/EquipmentPrinciple")
	public String EquipmentPrinciple(Model model) {

		return "EquipmentPrinciple";
	}
	// 删除文件夹
	// param folderPath 文件夹完整绝对路径

	public static void delFolder(String folderPath) {
		try {
			delAllFile(folderPath); // 删除完里面所有内容
			String filePath = folderPath;
			filePath = filePath.toString();
			java.io.File myFilePath = new java.io.File(filePath);
			myFilePath.delete(); // 删除空文件夹
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 删除指定文件夹下所有文件
	// param path 文件夹完整绝对路径
	public static boolean delAllFile(String path) {
		boolean flag = false;
		File file = new File(path);
		if (!file.exists()) {
			return flag;
		}
		if (!file.isDirectory()) {
			return flag;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
				delFolder(path + "/" + tempList[i]);// 再删除空文件夹
				flag = true;
			}
		}
		return flag;
	}

	public static void main(String[] args) throws IOException {
		Runtime.getRuntime().exec("cmd /c mysqldump -h127.0.0.1 -uroot -ptechysky123 hhmse sys_user>d:\\hhmse.sql");
	}
}
